from datetime import date, timedelta

from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView

from apps.goods.models import GoodsVisitCount
from apps.meiduo_admin.serializers.statistical import GoodsSerializer
from apps.users.models import User


class TotalView(APIView):
    permission_classes = [IsAdminUser]

    # 管理员认证识别
    # 统计用户
    def get(self, request):
        count = User.objects.filter(is_staff=False).count()
        return Response({
            'count': count,
            'date': date.today(),
        })


class UserDayCountView(APIView):
    permission_classes = [IsAdminUser]

    # 统计今天新增用户
    def get(self, request):
        today = date.today()
        count = User.objects.filter(is_staff=False, date_joined__gte=today).count()
        return Response({
            'count': count,
            'date': today,

        })


class UserActiveCountView(APIView):
    permission_classes = [IsAdminUser]

    # 统计今天活跃的用户
    def get(self, request):
        today = date.today()
        count = User.objects.filter(is_staff=False, last_login__gte=today).count()
        return Response({
            "count": count,
            "date": today
        })


class UserOrderCountView(APIView):
    permission_classes = [IsAdminUser]

    # 统计今天下单的用户
    def get(self, request):
        today = date.today()
        # 根据订单表中的外键取出来订单的下单事件遭遇今天的然后去重
        count = User.objects.filter(orders__create_time__gte=today).distinct().count()

        return Response({
            'count': count,
            'date': today,
        })


class UserMonthCountView(APIView):
    permission_classes = [IsAdminUser]

    # 月新增用户

    def get(self, request):
        today = date.today()
        count_list = []
        for i in range(29, -1, -1):
            day_begin = today - timedelta(days=i)
            day_end = day_begin + timedelta(days=1)
            day_count = User.objects.filter(is_staff=False, date_joined__gte=day_begin, date_joined__lt=day_end).count()
            count_list.append({
                'date': day_begin,
                'count': day_count,
            })
        return Response(count_list)


class GoodsDayView(ListAPIView):
    # 查询日分类商品的访问量
    queryset = GoodsVisitCount.objects.filter(date=date.today())
    serializer_class = GoodsSerializer
